package cn.com.gridinfo.sooc.core.expand.signin.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.core.expand.callname.bean.ClassInfo;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.core.expand.signin.adapter.TodaySignAdapter;
import cn.com.gridinfo.sooc.utils.CompressBitmap;
import cn.com.gridinfo.sooc.utils.DateUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;
import cn.com.zxing.activity.CaptureActivity;

/**
 * 今日签到的Fragment
 *
 * @author yingchunli
 */
public class TodaySignFragment extends BaseSoocFragment {

    View view;//当前布局
    @InjectView(R.id.searchSignin_todaysign)
    ClearEditText searchContent;//搜索内容
    @InjectView(R.id.search_leftline)
    View search_leftline;//搜索前面的线
    @InjectView(R.id.saoma_layout)
    LinearLayout saoma_layout;//扫码区域
    @InjectView(R.id.list_todaysign)
    UltimateRecyclerView listTodaysign;//列表
    CallNameDao dao;
    TodaySignAdapter adapter;//适配器
    LinearLayoutManager linearLayoutManager;//布局管理器
    int maxLastPositon;//最后数据位置
    EditText xm, xh, bj;//学生姓名 学号 班级
    TextView agreeBtn, disagreeBtn;//确定按钮，取消按钮
    LinearLayout class_pz;//课堂拍照区域
    ImageView pzPic;//签到图片
    ImageView pqqdIcon;//拍照签到的点击图
    String imei;//设备标识码
    View viewDialog;//签到对话框
    String signFileName = "sign.jpg";//头像名称;
    String signFileDir;//头像目录
    private String ktid = null;//课堂id
    private final int INTENT_CAREMA = 999;//跳转照相页面
    private final int INTENT_SAOMA = 1000;//去扫码
    private static final int REQUEST_CUT = 1001;//压缩裁剪
    TextView kcmc;//课程名称
    TextView lsmc;//老师名称
    TextView sksj;//上课日期
    int qdsf = -1;//签到方式，默认-1
    MaterialDialog dialog;//签到的对话框
    int isPhoto = 0;//是否有照片
    @InjectView(R.id.blank_icon)
    ImageView imgBlank;//空白页的图片
    @InjectView(R.id.tipBlank)
    TextView tipBlank;//空白页提示
    File signPhoto;//压缩后的签到图片

    public static TodaySignFragment newInstance(String info) {
        Bundle args = new Bundle();
        TodaySignFragment fragment = new TodaySignFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.expand_sign_todaysign, null);
        ButterKnife.inject(this, view);
        dao = new CallNameDao(this);
        //初始化列表
        linearLayoutManager = new LinearLayoutManager(getActivity());
        listTodaysign.setLayoutManager(linearLayoutManager);
        //发送请求  获取列表数据
        PageConst.pageNo = 1;
        PageConst.pageSize = 10;
        dao.getMySign(0, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_FIRST);

        //按键完成监听
        searchContent.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearchClick();
                }
                return false;
            }
        });
        return view;
    }

    /**
     * 初始化列表数据
     */
    private void initView() {
        adapter = new TodaySignAdapter(getActivity(), dao.getClassInfoList());
        listTodaysign.setAdapter(adapter);
        listTodaysign.enableLoadmore();
        listTodaysign.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                PageConst.pageNo = 1;
                if (searchContent.getText().toString().isEmpty()) {
                    //搜索内容为空 ，表明是获取列表
                    dao.getMySign(0, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
                } else {
                    //搜索内容不为空时，表明是搜索列表数据
                    dao.getMySign(2, searchContent.getText().toString().trim(), PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
                }
                linearLayoutManager.scrollToPosition(0);
            }
        });
        listTodaysign.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (PageConst.pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    if (searchContent.getText().toString().isEmpty()) {
                        //搜索内容为空 ，表明是获取列表
                        dao.getMySign(0, null, ++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PULLUP);
                    } else {
                        //搜索内容不为空时，表明是搜索列表数据
                        dao.getMySign(2, searchContent.getText().toString().trim(), ++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PULLUP);
                    }
                } else {
                    adapter.loadNoDataView();
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
        });
        goSign();//去签到动作
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            //关闭进度条
            showProgress(false, true);

            if (dao.getStatus().equals("0")) {
                switch (requestCode) {
                    case CodeConst.EXPAND_GET_SIGNLIST_FIRST://获取列表数据
                        initView();
                        break;
                    case CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN://获取列表  下拉请求
                        listTodaysign.setRefreshing(false);
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            listTodaysign.hideEmptyView();

                        } else {
                            //无数据处理

                            if (searchContent.getText().toString().trim().equals("")) {
                                imgBlank.setImageResource(R.mipmap.blank_sign);
                                tipBlank.setText("今天还没有签到哦~");
                            } else {
                                imgBlank.setImageResource(R.mipmap.blank_search);
                                tipBlank.setText("没有找到相关课堂");
                            }
                            listTodaysign.showEmptyView();
                        }
                        //刷新数据
                        adapter.refresh(dao.getClassInfoList());
                        if (dao.getClassInfoList().size() > (PageConst.pageSize - 1))
                            //数据大于每页显示的条数,则重新开启加载更多
                            adapter.loadMoreDataView();
                        else {
                            //数据小于当前页的话则不显示加载更多
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);
                        }
                        break;
                    case CodeConst.EXPAND_GET_SIGNLIST_PULLUP://获取列表  上拉请求
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            //加载更多
                            adapter.loadmore(dao.getClassInfoList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                    case CodeConst.EXPAND_SIGN:
                        //签到成功
                        MessageUtils.showRightImageShortToast(getActivity(), "签到成功");
                        dialog.dismiss();
                        isPhoto = 0;
                        dao.getMySign(0, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
                        searchContent.setText("");
                        break;
                    case CodeConst.EXPAND_SIGNINFO://获取签到课堂的信息
                        qdsf = 1;//设置签到方式为1，即表示扫码签到
                        kcmc.setText(dao.getClassInfo().getKcmc());
                        lsmc.setText(dao.getClassInfo().getLsmc());
                        sksj.setText(DateUtil.getDateFromDatestamp(dao.getClassInfo().getSksj()));
                        xm.setText(dao.getStudent().getXsxm());
                        xh.setText(dao.getStudent().getXh());
                        bj.setText(dao.getStudent().getBj());
                        pzPic.setImageBitmap(null);

                        xm.requestFocus();
                        xm.clearFocus();
                        xh.requestFocus();
                        xh.clearFocus();
                        bj.requestFocus();
                        bj.clearFocus();
                        xm.setSelection(xm.getText().toString().length());
//                        bj.requestFocus();
//                        bj.setSelection(bj.getText().toString().length());

                        showDialog();//显示对话框
                        //判断是否显示拍照区域
                        if (dao.getClassInfo().getKtxc().equals("1")) {
                            class_pz.setVisibility(View.VISIBLE);
                        } else {
                            class_pz.setVisibility(View.GONE);
                        }
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "请求数据异常");
        }
    }


    /**
     * 去签到
     */
    private void goSign() {
        //获取设备标识码
        try {
            TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(getActivity().TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (SecurityException e) {
            e.printStackTrace();
        } finally {
            if (imei == null || "".equals(imei)) {
                imei = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        }
        Log.d("imei->" + imei);
        setDialog();//对话框初始化
        adapter.setmOnItemClickLitener(new TodaySignAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, final ClassInfo classInfo) {
                ktid = classInfo.getKtid();//课堂id赋值
                kcmc.setText(classInfo.getKcmc());//课程名称
                lsmc.setText(classInfo.getLsmc());//老师名称
                sksj.setText(classInfo.getSksj());//上课日期
                xm.setText("");
                xh.setText("");
                bj.setText("");
                if (classInfo.getQdms().equals("1")) {
                    class_pz.setVisibility(View.VISIBLE);
                } else {
                    class_pz.setVisibility(View.GONE);
                }
                pzPic.setImageBitmap(null);
                showDialog();
            }
        });
    }

    /**
     * 显示签到的对话框
     */
    void showDialog() {
        Log.d("ktid->" + ktid);
        //弹出签到对话框

        dialog = new MaterialDialog.Builder(getActivity())
                .backgroundColor(Color.WHITE)
                .customView(viewDialog, true)
                .positiveText(R.string.agree)
                .positiveColor(getResources().getColor(R.color.colorAccent))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        //签到动作
                        if (judge()) {
                            if (class_pz.getVisibility() == View.GONE) {
                                Log.d("签到，没照片");
                                if (qdsf == 1) {
                                    //扫码签到
                                    dao.goSign(ktid, xm.getText().toString().trim(), xh.getText().toString().trim(),
                                            bj.getText().toString().trim(), "1", imei, CodeConst.EXPAND_SIGN);
                                } else {
                                    dao.goSign(ktid, xm.getText().toString().trim(), xh.getText().toString().trim(),
                                            bj.getText().toString().trim(), "0", imei, CodeConst.EXPAND_SIGN);
                                }
                                //显示加载进度条
                                showProgress(true, true);
                            } else {
                                Log.d("签到，带有图片");
                                if (qdsf == 1) {
                                    //扫码签到
                                    dao.goSignWithPhoto(ktid, xm.getText().toString().trim(), xh.getText().toString().trim(),
                                            bj.getText().toString().trim(), "1", imei, signPhoto, CodeConst.EXPAND_SIGN);
                                } else {
                                    dao.goSignWithPhoto(ktid, xm.getText().toString().trim(), xh.getText().toString().trim(),
                                            bj.getText().toString().trim(), "0", imei, signPhoto, CodeConst.EXPAND_SIGN);
                                }
                                //显示加载进度条
                                showProgress(true, true);
                            }
                        }
                    }
                })
                .autoDismiss(false)
                .show();
    }

    /**
     * 判断 姓名 学号 班级 是否为空
     *
     * @return
     */
    boolean judge() {
        if (xm.getText().toString().trim().equals("")) {
            MessageUtils.showImageShortToast(getActivity(), "姓名不能为空!");
            return false;
        } else if (xh.getText().toString().trim().equals("")) {
            MessageUtils.showImageShortToast(getActivity(), "学号不能为空!");
            return false;
        } else if (bj.getText().toString().trim().equals("")) {
            MessageUtils.showImageShortToast(getActivity(), "班级不能为空!");
            return false;
        }
        if (class_pz.getVisibility() == View.VISIBLE) {
            //判断是否含有照片
            if (isPhoto == 0) {
                MessageUtils.showImageShortToast(getActivity(), "照片不能为空!");
                return false;
            }
        }
        return true;
    }

    /**
     * 对话框初始化
     */
    private void setDialog() {
        viewDialog = LayoutInflater.from(getActivity()).inflate(R.layout.expand_sign_dialog, null);
        kcmc = (TextView) viewDialog.findViewById(R.id.kcmc_sign_dialog);
        lsmc = (TextView) viewDialog.findViewById(R.id.lsmc_sign_dialog);
        sksj = (TextView) viewDialog.findViewById(R.id.skrq_sign_dialog);
        xm = (EditText) viewDialog.findViewById(R.id.xm_sign_dialog);
        xh = (EditText) viewDialog.findViewById(R.id.xh_sign_dialog);
        bj = (EditText) viewDialog.findViewById(R.id.banji_sign_dialog);
        pzPic = (ImageView) viewDialog.findViewById(R.id.qdpz_Img);
        pqqdIcon = (ImageView) viewDialog.findViewById(R.id.ktpz_sign_dialog);
        class_pz = (LinearLayout) viewDialog.findViewById(R.id.class_pz);//课堂拍照区域
        //课堂拍照的点击事件
        viewDialog.findViewById(R.id.ktpz_sign_dialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goCamara();//打开相机照相
            }
        });
    }

    /**
     * 打开照相机照相
     */
    private void goCamara() {
        File fileDir = new File(Environment.getExternalStorageDirectory() + "/sooc/tmpSign/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        signFileDir = fileDir.getAbsolutePath();
        signFileName  = DateUtil.getCurrDateStamp()+".jpg";
        String tempPath = signFileDir + "/" + signFileName;
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
            //判断是否有SD卡
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                    .fromFile(new File(tempPath)));
            intent.putExtra("return-data", true);
            startActivityForResult(intent, INTENT_CAREMA);
            AnimUtil.intentSlidIn(getActivity());
        } else {
            MessageUtils.showImageShortToast(getActivity(), "没有SD卡");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("resultCode=" + resultCode);
        switch (requestCode) {
            case INTENT_CAREMA:
                //从照相页面返回
                if (resultCode == Activity.RESULT_OK) {
                    Log.d("从照相页面返回");
                    File tempFile = new File(signFileDir + "/" + signFileName);
                    setImage(tempFile.getAbsolutePath());//显示图片
//                    startPhotoZoom(Uri.fromFile(tempPath));
                    isPhoto = 1;
                } else {
                    Log.d("取消");
                    if (isPhoto != 1)
                        isPhoto = 0;
                }
                break;
            case REQUEST_CUT://压缩完返回的结果
                if (data != null) {
//                    setPicToView(data);
//                    setImage(data);//显示图片

                }

                break;
            case INTENT_SAOMA:
                //从扫码界面返回 并且没有点击取消按钮
                if (data != null && !data.getStringExtra("result").equals("0")) {
                    ktid = "";
                    ktid = data.getStringExtra("result");
                    Log.d("saoma ktid=" + ktid);
                    dao.getSignInfo(ktid, CodeConst.EXPAND_SIGNINFO);//获取课堂签到的信息
                }
                break;
        }
    }

    /**
     * 显示拍照后的图片
     */
    public void setImage(String filePath) {
//        Bundle extras = picdata.getExtras();
//        if (extras != null) {
//        Bitmap photo = BitmapFactory.decodeFile(filePath, CompressBitmap.getBitmapOption(2));
////            Bitmap photo = extras.getParcelable("data");

//
//        File file = CompressBitmap.saveBitmap(photo, DateUtil.getCurrDateStamp() + ".jpg");
        //压缩图片
        Bitmap bm = CompressBitmap.compressBitmap(filePath);
        pzPic.setImageBitmap(bm);
        //把图片存储到本地
        signPhoto = CompressBitmap.saveBitmap(bm, "tmp_pic_sign_cut" + ktid + ".jpg");
//        }


    }

    /**
     * 二维码扫描
     */
    @OnClick(R.id.saoma_icon)
    void onSaomaClick() {
//        MessageUtils.showImageShortToast(getActivity(), "正在打开摄像头，请稍后。。。");
        //打开照相机
        startActivityForResult(new Intent(getActivity(), CaptureActivity.class), INTENT_SAOMA);
        AnimUtil.intentSlidIn(getActivity());
    }

    /**
     * 判断必填内容是否为空，确定注册按钮处于什么状态
     * 当必填内容全不为空时，注册按钮才处于可点击状态，否则，不可点击
     */
    @OnTextChanged(value = R.id.searchSignin_todaysign, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        //搜索内容不为空时，去搜索
        if (!searchContent.getText().toString().trim().equals("")) {
            search_leftline.setVisibility(View.VISIBLE);
            saoma_layout.setVisibility(View.GONE);
        } else {
            //搜索内容为空时
            search_leftline.setVisibility(View.GONE);
            saoma_layout.setVisibility(View.VISIBLE);
            //发送请求  获取列表数据
            PageConst.pageNo = 1;
            PageConst.pageSize = 10;
            dao.getMySign(0, null, PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
        }
    }

    /**
     * 搜索按钮的点击
     */
    @OnClick(R.id.search_todaysign)
    void onSearchClick() {
        //发送请求  去搜索
        if (!searchContent.getText().toString().trim().equals("")) {
            PageConst.pageNo = 1;
            dao.getMySign(2, searchContent.getText().toString().trim(), PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_SIGNLIST_PUSHDOWN);
            //隐藏软键盘
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchContent.getWindowToken(), 0);
            qdsf = -1;
        }

    }

    //压缩裁剪
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CUT);

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}